package com.example.yichuangyun.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.media3.common.MediaItem;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;

import com.example.yichuangyun.R;
import com.example.yichuangyun.databinding.ActivityTestBinding;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class TestActivity extends BaseActivity<ActivityTestBinding, BaseViewModel> {

    private ExoPlayer player;
    private Handler handler;
    private Runnable updateSeekBarRunnable;
    private List<MediaItem> mediaItemList;
    private int currentIndex = 0;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this,BaseViewModel.class);
    }

    @Override
    protected void initInject() {
getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        handler = new Handler(Looper.getMainLooper());

        // 初始化媒体列表
        mediaItemList = new ArrayList<>();
        mediaItemList.add(MediaItem.fromUri(Uri.parse("https://ycydown.yikaiye.net/174591978811918930531123?e=1746600055&token=1b-_j_cFBvs3NOHACwelmEXzIApAYsC34hPx8zfc:NoZkTrrSZLsG8DF0Vzub-d_SEaI=")));
        mediaItemList.add(MediaItem.fromUri(Uri.parse("https://ycydown.yikaiye.net/174651101707017610551105?e=1746600347&token=1b-_j_cFBvs3NOHACwelmEXzIApAYsC34hPx8zfc:U1UMmeB2M2IC6ZBApxCS6anfNgU=")));
        mediaItemList.add(MediaItem.fromUri(Uri.parse("https://ycydown.yikaiye.net/174539755734618930531123?e=1746600385&token=1b-_j_cFBvs3NOHACwelmEXzIApAYsC34hPx8zfc:kR-izU6xIvPyjV_CPT4ax74yoXo=")));

        // 创建 ExoPlayer 实例
        player = new ExoPlayer.Builder(this).build();

        // 准备并播放当前音频
        prepareAndPlay(currentIndex);

        // 设置播放暂停按钮监听器
        binding.playPauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player.isPlaying()) {
                    player.pause();
                    binding.playPauseButton.setText("播放");
                } else {
                    player.play();
                    binding.playPauseButton.setText("暂停");
                }
            }
        });

        // 设置上一条按钮监听器
        binding.prevButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentIndex > 0) {
                    currentIndex--;
                    prepareAndPlay(currentIndex);
                }
            }
        });

        // 设置下一条按钮监听器
        binding.nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentIndex < mediaItemList.size() - 1) {
                    currentIndex++;
                    prepareAndPlay(currentIndex);
                }
            }
        });

        // 设置 SeekBar 监听器
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    player.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 停止更新 SeekBar
                handler.removeCallbacks(updateSeekBarRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复更新 SeekBar
                updateSeekBar();
            }
        });

        // 开始更新 SeekBar
        updateSeekBar();
    }
    @SuppressLint("UnsafeOptInUsageError")
    private void prepareAndPlay(int index) {
        MediaItem mediaItem = mediaItemList.get(index);
        // 创建 DataSource
        DefaultDataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);
        // 创建 MediaSource
        ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(mediaItem);
        // 准备播放器
        player.setMediaSource(mediaSource);
        player.prepare();
        player.play();
        binding.playPauseButton.setText("暂停");
    }

    private void updateSeekBar() {
        if (player != null) {
            int currentPosition = (int) player.getCurrentPosition();
            int duration = (int) player.getDuration();
            binding.seekBar.setMax(duration);
            binding.seekBar.setProgress(currentPosition);

            updateSeekBarRunnable = new Runnable() {
                @Override
                public void run() {
                    updateSeekBar();
                }
            };
            handler.postDelayed(updateSeekBarRunnable, 1000);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            // 释放 ExoPlayer 资源
            player.release();
            player = null;
        }
        if (handler != null) {
            handler.removeCallbacks(updateSeekBarRunnable);
        }
    }
}